package entity

import (
	"fmt"
	"gluenet/modules/manager/server/domain/po"
	"gluenet/modules/manager/server/domain/vo"
	"gluenet/modules/manager/server/infra"
	"time"
)

type Agent struct {
	infra.Entity `xorm:"-"`
	po.Agent     `xorm:"extends"`
	Tags         []*po.Tag `xorm:"-"`
}

func (r *Agent) Identity() string {
	return r.Agent.GUID
}

func (r *Agent) MarkedTag(key, value string) error {
	return nil
}

func (r *Agent) NewFrom(ag *vo.AgentRegisterReq, guid string) {
	//r.ID = infra.NewID()
	r.GUID = guid
	r.Platform = ag.Platform
	r.Role = ag.Role
	r.HostName = ag.HostName
	r.AreaID = ag.AreaID
}

func (r *Agent) ShowRuntime() (*vo.AgentRuntimeRes, error) {
	var runtime = &vo.AgentRuntimeRes{
		GUID:        r.GUID,
		Name:        r.HostName,
		Platform:    r.Platform,
		CpuUsage:    10,
		Cores:       1,
		MemSize:     1024 * 1024 * 100,
		MemUsage:    10,
		RunningTime: time.Now().Unix() - r.RegisterTime.Unix(),
	}
	drvi, ok := r.DetailRepoValue.(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("detail is not map[string]interface{}")
	}

	platform, ok := drvi["platform"]
	if !ok {
		return nil, fmt.Errorf("detail is not contain platform")
	}

	switch platform.(string) {
	case PlatformKubernetes:
		nodesi, ok := drvi["nodes"]
		if !ok {
			return nil, fmt.Errorf("detail is not contain nodes")
		}
		nodes, ok := nodesi.([]interface{})
		if !ok {
			return nil, fmt.Errorf("detail is not []interface{}")
		}
		runtime.Hosts = float64(len(nodes))
		hostDetail := make([]map[string]interface{}, len(nodes))
		for k, v := range nodes {
			hostDetail[k] = map[string]interface{}{
				v.(string): struct{}{},
			}
		}
		runtime.HostsDetail = hostDetail
	case PlatformGluenets:
		runtime.Hosts = 1
		nodeName, ok := drvi["host_name"]
		if !ok {
			return nil, fmt.Errorf("detail is not contain host_name")
		}
		hostDetail := make([]map[string]interface{}, 1)
		hostDetail[0] = map[string]interface{}{
			nodeName.(string): struct{}{},
		}
		runtime.HostsDetail = hostDetail
	}

	return runtime, nil
}
